package org.openharmony.qttool;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class QtSDK implements Serializable {
    private final Map<String, String> qtInfo = new HashMap<>();

    private final String qmakePath;
    private static final String QT_VERSION = "QT_VERSION";
    private static final String QT_INSTALL_PREFIX = "QT_INSTALL_PREFIX";

    private String arch = "arm64_v8a";

    private boolean sdkValid = false;


    public QtSDK(String path) {
        qmakePath = path;
        ProcessBuilder processBuilder = new ProcessBuilder(path, "-query");

        try {
            Process process = processBuilder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                int colonIndex = line.indexOf(":");
                String key = line.substring(0, colonIndex);
                String value = line.substring(colonIndex + 1);
                if (!value.isEmpty()) {
                    qtInfo.put(key, value);
                }
            }
        } catch (IOException e) {
            Utils.handleException(e);
        }
        sdkValid = detectQtArch();
    }

    public String prefix() {
        return qtInfo.get(QT_INSTALL_PREFIX);
    }

    public String version() {
        return qtInfo.get(QT_VERSION);
    }

    @Override
    public String toString() {
        return qmakePath;
    }

    public boolean isValid() {
        return sdkValid;
    }

    public String getArch() {
        return this.arch;
    }

    private boolean detectQtArch() {
        Path startingDir = Paths.get(prefix(), "/lib");
        List<String> matchingFiles = new ArrayList<>();
        try {
            Files.walkFileTree(startingDir, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    String fileName = file.getFileName().toString();
                    if (fileName.startsWith("libQt5Core") || fileName.startsWith("libQt6Core")) {
                        if (fileName.endsWith(".so"))
                            matchingFiles.add(file.toString());
                    }
                    return FileVisitResult.CONTINUE;
                }
                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) {
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            Utils.handleException(e);
        }
        if (matchingFiles.isEmpty())
            return false;
        arch = Utils.archOfBinary(matchingFiles.get(0));
        return arch.compareTo("arm64-v8a") == 0 ||
                arch.compareTo("armeabi-v7a") == 0 ||
                arch.compareTo("x86_64") == 0;
    }

    public String designer() {
        String osName = System.getProperty("os.name").toLowerCase();
        String designerTool = "/bin/designer";
        String finalDesignerTool;
        if (osName.contains("win")) {
            finalDesignerTool = designerTool + ".exe";
        } else {
            finalDesignerTool = designerTool;
        }
        Path p = Paths.get(prefix() + finalDesignerTool);
        if (Files.exists(p))
            return p.toString();
        return null;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        QtSDK other = (QtSDK) obj;

        return Objects.equals(this.prefix(), other.prefix());
    }
}
